package com.youxin.cpcenter.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.youxin.busfoundation.bean.BusinessMessages;
import com.youxin.busfoundation.bean.ResponseObject;
import com.youxin.busfoundation.bean.ent.QueryEntAdminStatusBean;
import com.youxin.busfoundation.bean.ent.ReponseAdminStausBean;
import com.youxin.busfoundation.bean.leads.QueryLeadsViewBean;
import com.youxin.busfoundation.bean.leads.RequestAssignLeadsBean;
import com.youxin.busfoundation.bean.leads.RequestLeadsBean;
import com.youxin.busfoundation.bean.leads.RequestLeadsHistoryBean;
import com.youxin.busfoundation.bean.leads.RequestLeadsPoolBean;
import com.youxin.busfoundation.bean.leads.RequestTransferLeadsBean;
import com.youxin.busfoundation.bean.leads.ResponseLeadsHistoryBean;
import com.youxin.busfoundation.bean.login.UserInfo;
import com.youxin.busfoundation.common.BusinessDataException;
import com.youxin.busfoundation.common.BusinessException;
import com.youxin.busfoundation.common.LoginAuth;
import com.youxin.busfoundation.common.es.SearchComapny;
import com.youxin.busfoundation.common.es.SearchContact;
import com.youxin.busfoundation.common.es.bean.CompanyInfoBean;
import com.youxin.busfoundation.common.es.bean.ContactCountBean;
import com.youxin.busfoundation.enums.EnterpriseManagerType;
import com.youxin.busfoundation.enums.FollowLeadsStatus;
import com.youxin.busfoundation.enums.LeadsPoolType;
import com.youxin.busfoundation.model.BaseEntCluePool;
import com.youxin.busfoundation.model.EntCluePoolBean;
import com.youxin.busfoundation.utils.ArrayBusUtils;
import com.youxin.busfoundation.utils.bean.YouxinBeanUtils;
import com.youxin.cpcenter.bean.MemberQueryListBean;
import com.youxin.cpcenter.bean.member.MemberInfo;
import com.youxin.cpcenter.common.dbcache.CacheDataObject;
import com.youxin.cpcenter.dao.TbEntCluePoolCompanyMapper;
import com.youxin.cpcenter.dao.TbEntCluePoolLogMapper;
import com.youxin.cpcenter.dao.TbEntCluePoolPersonalMapper;
import com.youxin.cpcenter.dao.TbEntMemberInfoMapper;
import com.youxin.cpcenter.dao.TbMemberInfoMapper;
import com.youxin.cpcenter.model.TbEntCluePoolCompany;
import com.youxin.cpcenter.model.TbEntCluePoolLog;
import com.youxin.cpcenter.model.TbEntCluePoolPersonal;
import com.youxin.cpcenter.model.TbEntLeadsStat;
import com.youxin.cpcenter.model.TbEntMemberInfo;
import com.youxin.cpcenter.model.TbMemberInfo;
import com.youxin.cpcenter.service.CapitalService;
import com.youxin.cpcenter.service.ClassifyService;
import com.youxin.cpcenter.service.LeadsNumberService;
import com.youxin.cpcenter.service.LeadsService;
import com.youxin.cpcenter.service.LeadsStatService;
import com.youxin.cpcenter.utils.MemberRightsUtils;
import com.youxin.foundation.data.Tuple;
import com.youxin.foundation.db.utils.KeyGenerationUtils;
import com.youxin.foundation.utils.ArrayUtils;
import com.youxin.foundation.utils.StringUtils;
import com.youxin.foundation.utils.collections.CollectionsUtils;

/**
 * @desc 线索管理
 * @author yingde.cao
 * @update 2018-1-5
 */
@Service("leadsService")
public class LeadsServiceImpl extends BaseServiceImpl implements LeadsService {

	@Autowired
	private TbEntCluePoolCompanyMapper tbEntCluePoolCompanyMapper;
	@Autowired
	private TbEntCluePoolLogMapper tbEntCluePoolLogMapper;
	@Autowired
	private TbEntCluePoolPersonalMapper tbEntCluePoolPersonalMapper;
	@Autowired
	private TbMemberInfoMapper tbMemberInfoMapper;
	@Autowired
	private TbEntMemberInfoMapper tbEntMemberInfoMapper;
	@Autowired
	private CapitalService capitalService;
	@Autowired
	private LeadsNumberService leadsNumberService;
	@Autowired
	private LeadsStatService leadsStatService;
	@Autowired
	private ClassifyService classifyService;

	/**
	 * @desc 添加线索,分为两种,企业管理员和会员;都可以添加线索
	 * @param bean
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseObject addLeads(RequestLeadsBean bean) {
		UserInfo userInfo = LoginAuth.getUserInfo();
		if (!capitalService.isCanAddLeads(userInfo.getEntIdentifyId())) {
			throw new BusinessDataException(BusinessMessages.SERVICE_EXPIRES);
		}
		return addLeadsDetail(bean, userInfo);
	}

	/**
	 * @desc 添加线索池
	 * @param bean
	 * @param userInfo
	 * @return
	 */
	public ResponseObject addLeadsDetail(RequestLeadsBean bean, UserInfo userInfo) {
		TbMemberInfo memberInfo = null;
		boolean isAdmin = userInfo.isAdmin();
		FollowLeadsStatus leadsStatus = FollowLeadsStatus.UnFollow;
		if (isAdmin) {
			memberInfo = MemberRightsUtils.isAdmin(tbMemberInfoMapper);
		} else {
			memberInfo = MemberRightsUtils.isMemberIdentifyAndPassed(tbMemberInfoMapper);
			leadsStatus = FollowLeadsStatus.Flollowing;
		}

		long poolId = KeyGenerationUtils.generateKey();
		TbEntCluePoolCompany poolCompany = new TbEntCluePoolCompany();
		poolCompany.setId(poolId);
		poolCompany.setEntIdentifyId(userInfo.getEntIdentifyId());

		poolCompany.setCollectCompanyUid(bean.getCompanyUid());
		poolCompany.setCollectCompanyName(StringUtils.isNullSetEmpty(bean.getCompanyName()));
		poolCompany.setCollectShortName(bean.getShortName());

		poolCompany.setCompanyUid(userInfo.getCompanyUid());
		poolCompany.setCompanyName(userInfo.getCompanyName());
		poolCompany.setStatus(leadsStatus.getValue());

		poolCompany.setCreateMemberName(memberInfo.getUsername());
		poolCompany.setCreateMemberId(memberInfo.getId());
		poolCompany.setCreateEntMemberId(userInfo.getEntMemberId());
		poolCompany.setEntMemberId(userInfo.getEntMemberId());
		long time = System.currentTimeMillis();
		/**
		 * 个人添加增加跟进人
		 */
		if (!isAdmin) {
			poolCompany.setMemberType(EnterpriseManagerType.Normal.getValue());
			poolCompany.setMemberId(memberInfo.getId());
			poolCompany.setEntMemberId(userInfo.getEntMemberId());
			poolCompany.setMemberName(memberInfo.getUsername());
			poolCompany.setCurrentFollowTime(time);
			poolCompany.setRealName(memberInfo.getRealname());
		} else {
			poolCompany.setMemberId(0L);
			poolCompany.setEntMemberId(0L);
			poolCompany.setMemberName("");
			poolCompany.setRealName("");
			poolCompany.setCurrentFollowTime(time);
			poolCompany.setMemberType(EnterpriseManagerType.Admin.getValue());
		}
		poolCompany.setMemberType(bean.getIsadmin());
		poolCompany.setAddTime(time);
		poolCompany.setUpdateTime(time);

		int rowEffected = tbEntCluePoolCompanyMapper.insertSelective(poolCompany);
		if (rowEffected != 1) {
			throw new BusinessException("添加到公司线索池失败");
		}
		TbEntCluePoolPersonal personal = null;
		if (!isAdmin) {
			personal = new TbEntCluePoolPersonal();
			BeanUtils.copyProperties(poolCompany, personal);
			rowEffected = tbEntCluePoolPersonalMapper.insertSelective(personal);
			if (rowEffected != 1) {
				throw new BusinessException("添加到个人线索池失败");
			}
		}

		TbEntCluePoolLog poolLog = new TbEntCluePoolLog();
		BeanUtils.copyProperties(poolCompany, poolLog);
		poolLog.setCluePoolId(poolCompany.getId());
		poolLog.setId(KeyGenerationUtils.generateKey());
		poolLog.setFlag(LeadsPoolType.Initial.getValue());
		poolLog.setRealName(memberInfo.getRealname());
		poolLog.setMemberId(memberInfo.getId());
		poolLog.setEntMemberId(userInfo.getEntMemberId());
		rowEffected = tbEntCluePoolLogMapper.insertSelective(poolLog);
		if (rowEffected != 1) {
			throw new BusinessException("添加到线索池失败");
		}

		leadsNumberService.decreaseLeadsNumber(userInfo.getEntIdentifyId());
		return ResponseObject.successObject();
	}

	/**
	 * @desc 公司线索池列表
	 */
	public ResponseObject listCompanyLeadsPool(RequestLeadsPoolBean bean) {
		UserInfo userInfo = LoginAuth.getUserInfo();
		MemberRightsUtils.isMemberIdentifyAndPassed(tbMemberInfoMapper);
		checkQueryLeadsBean(bean);
		/**
		 * 线索池统计
		 */
		TbEntLeadsStat stat = leadsStatService.getTbEntLeadsStat(userInfo.getEntIdentifyId());
		bean.setStat(stat);

		bean.setEntIdentifyId(userInfo.getEntIdentifyId());
		List<EntCluePoolBean> results = tbEntCluePoolCompanyMapper.select(bean);

		setLeadsCompanyInfo(results);
		// setLeadsAdminStatus(results);
		// viewLeadsService.updateLeadsPoolProperty(results,
		// userInfo.getEntMemberId());
		bean.setResults(CollectionsUtils.listClassConvert(results));
		return ResponseObject.successObject(bean);
	}

	private void checkQueryLeadsBean(RequestLeadsPoolBean bean) {
		if (bean.getBy() != null) {
			String by = bean.getBy();
			if ("create_time".equals(by)) {
				bean.setBy("add_time");
			} else if ("follow_status".equals(by)) {
				bean.setBy("status");
			}
			by = bean.getBy();
			if (!(by.equalsIgnoreCase("id") || by.equalsIgnoreCase("real_name") || by.equalsIgnoreCase("add_time")
					|| by.equalsIgnoreCase("status"))) {
				bean.setBy("id");
				bean.setOrderBy(1);
			}
		} else {
			bean.setBy("id");
			bean.setOrderBy(1);
		}
	}

	private void setLeadsAdminStatus(List<EntCluePoolBean> results) {
		List<Long> ids = results.stream().filter((item) -> {
			return item.getEntMemberId() > 0;
		}).map((item) -> {
			;
			return item.getEntMemberId();
		}).collect(Collectors.toList());

		if (ArrayUtils.isEmpty(ids)) {
			return;
		}

		List<EntCluePoolBean> filterResults = results.stream().filter((item) -> {
			return item.getEntMemberId() > 0;
		}).collect(Collectors.toList());
		QueryEntAdminStatusBean bean = new QueryEntAdminStatusBean();
		bean.setIds(ids);
		List<ReponseAdminStausBean> adminStatusList = tbEntMemberInfoMapper.selectAdminStausByIds(bean);
		for (EntCluePoolBean item : filterResults) {
			for (ReponseAdminStausBean adminStausBean : adminStatusList) {
				if (item.getEntMemberId().equals(adminStausBean.getId())) {
					item.setEnterpriseManager(adminStausBean.getEnterpriseManager());
					break;
				}
			}
		}
	}

	/**
	 * @desc 根据公司uid查找公司信息
	 * @description
	 * @param companyList
	 * @param companyUid
	 * @return
	 */
	private CompanyInfoBean findCompanyInfo(List<CompanyInfoBean> companyList, String companyUid) {
		if (companyList == null) {
			return null;
		}
		for (CompanyInfoBean item : companyList) {
			if (companyUid.equals(item.getUid())) {
				return item;
			}
		}
		return null;
	}

	/**
	 * @desc 线索的中的公司信息
	 * @description
	 * @param results
	 */
	private void setLeadsCompanyInfo(List<EntCluePoolBean> results) {
		List<CompanyInfoBean> companyList = null;
		/**
		 * 获取公司信息
		 */
		try {
			List<String> uids = results.stream().map(item -> item.getCollectCompanyUid()).collect(Collectors.toList());
			companyList = new SearchComapny<CompanyInfoBean>().queryCompanyInfosContact(uids);
		} catch (Exception e) {
			logger.error("setLeadsCompanyInfo:queryCompanyInfos", e);
		}

		List<? extends Bucket> contactList = null;
		try {
			List<String> uids = results.stream().map(item -> item.getCollectCompanyUid()).collect(Collectors.toList());
			contactList = new SearchContact<ContactCountBean>().queryContactCount(uids);
		} catch (Exception e) {
			logger.error("setLeadsCompanyInfo:queryContactCount", e);
		}
		/**
		 * 联系人列表
		 */
		Map<String, Long> contactMap = new HashMap<>();
		if (contactList != null) {
			for (Bucket item : contactList) {
				contactMap.put(item.getKeyAsString(), item.getDocCount());
			}
		}

		for (EntCluePoolBean item : results) {
			CompanyInfoBean companyInfoBean = findCompanyInfo(companyList, item.getCollectCompanyUid());
			if (companyInfoBean != null) {
				item.setShortName(companyInfoBean.getShortName());
				item.setScaleName(companyInfoBean.getScaleName());
				/**
				 * 分类名称
				 */
				List<String> industryNames = CacheDataObject.instance().getIndustryName(companyInfoBean.getIndustry(),
						classifyService);
				// List<String>
				// regionNames=searchService.getRegionNames(companyInfoBean.getArea());
				// EnterpriseScaleType.scaleNameOf(companyInfoBean.getScale())
				item.setIndustryName(ArrayBusUtils.getTopOne(industryNames));
			}

			Long contactCount = contactMap.get(item.getCollectCompanyUid());
			if (contactCount != null) {
				item.setContactNo(contactCount.intValue());
			}

		}
	}

	/**
	 * @desc 个人线索池
	 */
	public ResponseObject listPersonalLeadsPool(RequestLeadsPoolBean bean) {
		MemberRightsUtils.isMemberIdentifyAndPassed(tbMemberInfoMapper);
		UserInfo userInfo = LoginAuth.getUserInfo();
		checkQueryLeadsBean(bean);
		TbEntLeadsStat stat = leadsStatService.getTbEntLeadsStat(userInfo.getEntIdentifyId(),
				userInfo.getEntMemberId());
		bean.setStat(stat);
		bean.setEntIdentifyId(userInfo.getEntIdentifyId());
		bean.setEntMemberId(userInfo.getEntMemberId());
		List<EntCluePoolBean> results = tbEntCluePoolPersonalMapper.select(bean);
		setLeadsCompanyInfo(results);
		// setLeadsAdminStatus(results);
		// viewLeadsService.updateLeadsPoolProperty(results,
		// userInfo.getEntMemberId());
		bean.setResults(CollectionsUtils.listClassConvert(results));
		return ResponseObject.successObject(bean);
	}

	/**
	 * @desc 分配线索
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseObject assignLeads(RequestAssignLeadsBean bean) {
		UserInfo userInfo = LoginAuth.getUserInfo();
		TbMemberInfo adminInfo = MemberRightsUtils.isAdmin(tbMemberInfoMapper);
	   Tuple<TbMemberInfo, TbEntMemberInfo> tuple=MemberRightsUtils.isMemberIdentify(tbMemberInfoMapper, tbEntMemberInfoMapper
			   , bean.getMemberId(), userInfo.getCompanyUid());
	   TbMemberInfo memberInfo=tuple.getK();
	   TbEntMemberInfo entMemberInfo=tuple.getV();
		TbEntCluePoolCompany sourceEntity = tbEntCluePoolCompanyMapper.selectByPrimaryKey(bean.getId());
		if (sourceEntity == null) {
			throw new BusinessException("无法查询到线索信息");
		}
		if(sourceEntity.getEntIdentifyId()!=userInfo.getEntIdentifyId())
		{
			throw new BusinessException("当前线索不属于公司");
		}
		long time = System.currentTimeMillis();
		int rowEffected = 0;

		TbEntCluePoolCompany poolCompany = new TbEntCluePoolCompany();
		poolCompany.setId(bean.getId());
		poolCompany.setUpdateTime(time);
		poolCompany.setStatus(FollowLeadsStatus.Flollowing.getValue());
		poolCompany.setMemberId(memberInfo.getId());
		poolCompany.setEntMemberId(entMemberInfo.getId());
		poolCompany.setMemberName(memberInfo.getUsername());
		poolCompany.setRealName(memberInfo.getRealname());
		poolCompany.setCurrentFollowTime(time);
		poolCompany.setDescription(bean.getDescription());
		rowEffected = tbEntCluePoolCompanyMapper.updateByPrimaryKeySelective(poolCompany);
		if (rowEffected != 1) {
			throw new BusinessException("分配线索失败");
		}

		TbEntCluePoolPersonal poolPersonal = new TbEntCluePoolPersonal();
		BeanUtils.copyProperties(sourceEntity, poolPersonal);
		YouxinBeanUtils.copyPropertiesIgnoreNull(poolCompany, poolPersonal);
		
		rowEffected = tbEntCluePoolPersonalMapper.insertSelective(poolPersonal);
		if (rowEffected != 1) {
			throw new BusinessException("分配线索失败");
		}

		TbEntCluePoolLog poolLog = new TbEntCluePoolLog();
		BeanUtils.copyProperties(sourceEntity, poolLog);
		YouxinBeanUtils.copyPropertiesIgnoreNull(poolCompany, poolLog);
		poolLog.setLogTime(new Date());
		poolLog.setCluePoolId(sourceEntity.getId());
		poolLog.setId(KeyGenerationUtils.generateKey());
		poolLog.setFlag(LeadsPoolType.Assign.getValue());
		poolLog.setOldEntMemberId(userInfo.getEntMemberId());
		poolLog.setOldRealName(userInfo.getRealname());
		rowEffected = tbEntCluePoolLogMapper.insertSelective(poolLog);
		if (rowEffected != 1) {
			throw new BusinessException("分配线索失败");
		}

		return new ResponseObject();
	}

	/**
	 * @desc 删除线索
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseObject deleteLeads(RequestAssignLeadsBean bean) {
		//删除公司线索池记录
		tbEntCluePoolCompanyMapper.deleteByPrimaryKey(bean.getId());
        //删除个人线索池记录
		tbEntCluePoolPersonalMapper.deleteByPrimaryKey(bean.getId());
		//删除公司线索池关联记录
		tbEntCluePoolLogMapper.deleteByCluePoolId(bean.getId());
		return new ResponseObject();
	}

	/**
	 * @desc 认领线索
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseObject requestLeads(RequestAssignLeadsBean bean) {
		UserInfo userInfo = LoginAuth.getUserInfo();
		TbEntCluePoolCompany sourceEntity = tbEntCluePoolCompanyMapper.selectByPrimaryKey(bean.getId());
		if (sourceEntity == null) {
			throw new BusinessException("无法查询到线索信息");
		}
		if(sourceEntity.getEntIdentifyId()!=userInfo.getEntIdentifyId())
		{
			throw new BusinessException("当前线索不属于公司");
		}
		TbMemberInfo memberInfo = MemberRightsUtils.isMemberIdentifyAndPassed(tbMemberInfoMapper, tbEntMemberInfoMapper,
				userInfo.getId(), sourceEntity.getCompanyUid());

		long time = System.currentTimeMillis();
		int rowEffected = 0;
		TbEntCluePoolCompany poolCompany = new TbEntCluePoolCompany();
		poolCompany.setStatus(FollowLeadsStatus.Flollowing.getValue());
		poolCompany.setMemberId(memberInfo.getId());
		poolCompany.setEntMemberId(userInfo.getEntMemberId());
		poolCompany.setMemberName(memberInfo.getUsername());
		poolCompany.setRealName(memberInfo.getRealname());
		poolCompany.setDescription(bean.getDescription());
		poolCompany.setAddTime(time);
		poolCompany.setUpdateTime(time);
		poolCompany.setCurrentFollowTime(time);
		poolCompany.setId(bean.getId());
		rowEffected = tbEntCluePoolCompanyMapper.updateByPrimaryKeySelective(poolCompany);
		if (rowEffected != 1) {
			throw new BusinessException("认领线索失败");
		}

		TbEntCluePoolPersonal poolPersonal = new TbEntCluePoolPersonal();
		BeanUtils.copyProperties(sourceEntity, poolPersonal);
		YouxinBeanUtils.copyPropertiesIgnoreNull(poolCompany, poolPersonal);

		rowEffected = tbEntCluePoolPersonalMapper.insertSelective(poolPersonal);
		if (rowEffected != 1) {
			throw new BusinessException("认领线索失败");
		}

		TbEntCluePoolLog poolLog = new TbEntCluePoolLog();
		BeanUtils.copyProperties(sourceEntity, poolLog);
		YouxinBeanUtils.copyPropertiesIgnoreNull(poolCompany, poolLog);
		poolLog.setCluePoolId(sourceEntity.getId());
		poolLog.setId(KeyGenerationUtils.generateKey());
		poolLog.setFlag(LeadsPoolType.Request.getValue());

		rowEffected = tbEntCluePoolLogMapper.insertSelective(poolLog);
		if (rowEffected != 1) {
			throw new BusinessException("认领线索失败");
		}

		return new ResponseObject();
	}

	/**
	 * @desc 释放线索
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseObject releaseLeads(RequestAssignLeadsBean bean) {
		UserInfo userInfo = LoginAuth.getUserInfo();
		TbMemberInfo memberInfo = MemberRightsUtils.isMemberIdentifyAndPassed(tbMemberInfoMapper);
		TbEntCluePoolCompany sourceEntity = tbEntCluePoolCompanyMapper.selectByPrimaryKey(bean.getId());
		if (sourceEntity == null) {
			throw new BusinessException("无法查询到线索信息");
		}
		if(sourceEntity.getEntIdentifyId()!=userInfo.getEntIdentifyId())
		{
			throw new BusinessException("当前线索不属于公司");
		}
		MemberRightsUtils.isMemberIdentifyAndPassed(tbMemberInfoMapper);
		int rowEffected = tbEntCluePoolPersonalMapper.deleteByPrimaryKey(bean.getId());
		if (rowEffected != 1) {
			throw new BusinessException("释放线索失败.");
		}
		TbEntCluePoolCompany poolCompany = new TbEntCluePoolCompany();
		poolCompany.setUpdateTime(System.currentTimeMillis());
		poolCompany.setId(bean.getId());
		poolCompany.setMemberId(0L);
		poolCompany.setEntMemberId(0L);
		poolCompany.setMemberName("");
		poolCompany.setRealName("");
		poolCompany.setCurrentFollowTime(System.currentTimeMillis());
		poolCompany.setDescription(bean.getDescription());
		poolCompany.setStatus(FollowLeadsStatus.UnFollow.getValue());
		rowEffected = tbEntCluePoolCompanyMapper.updateByPrimaryKeySelective(poolCompany);
		if (rowEffected != 1) {
			throw new BusinessException("释放线索失败");
		}

		TbEntCluePoolLog poolLog = new TbEntCluePoolLog();
		BeanUtils.copyProperties(sourceEntity, poolLog);
		YouxinBeanUtils.copyPropertiesIgnoreNull(poolCompany, poolLog);
		poolLog.setCluePoolId(sourceEntity.getId());
		poolLog.setId(KeyGenerationUtils.generateKey());
		poolLog.setFlag(LeadsPoolType.ReleaseLeads.getValue());
		poolLog.setMemberId(memberInfo.getId());
		poolLog.setMemberName(memberInfo.getUsername());
		poolLog.setRealName(memberInfo.getRealname());
		poolLog.setEntMemberId(userInfo.getEntMemberId());
		rowEffected = tbEntCluePoolLogMapper.insertSelective(poolLog);
		if (rowEffected != 1) {
			throw new BusinessException("释放线索失败");
		}

		return new ResponseObject();
	}

	/**
	 * @desc 线索状态变化
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseObject changeLeadsStatus(RequestAssignLeadsBean bean) {
		UserInfo userInfo = LoginAuth.getUserInfo();
		TbMemberInfo memberInfo = MemberRightsUtils.isMemberIdentifyAndPassed(tbMemberInfoMapper);
		TbEntCluePoolCompany sourceEntity = tbEntCluePoolCompanyMapper.selectByPrimaryKey(bean.getId());
		if (sourceEntity == null) {
			throw new BusinessException("无法查询到线索信息");
		}

		if (bean.getStatus() == bean.getOldStatus()) {
			throw new BusinessException("线索状态没有发生变化");
		}

		if (sourceEntity.getStatus().shortValue() != bean.getOldStatus()) {
			throw new BusinessException("线索原状态可能被其他成员修改");
		}
		long time = System.currentTimeMillis();
		TbEntCluePoolPersonal poolPersonal = new TbEntCluePoolPersonal();
		poolPersonal.setId(bean.getId());
		poolPersonal.setUpdateTime(time);
		poolPersonal.setDescription(bean.getDescription());

		FollowLeadsStatus followLeadsStatus = FollowLeadsStatus.valueOf(bean.getStatus());
		if (followLeadsStatus == null) {
			throw new BusinessException("无效的跟进状态");
		}
		poolPersonal.setStatus(bean.getStatus());
		int rowEffected = tbEntCluePoolPersonalMapper.updateByPrimaryKeySelective(poolPersonal);
		if (rowEffected != 1) {
			throw new BusinessException("更新线索状态失败");
		}

		TbEntCluePoolCompany tbEntCluePoolCompany = new TbEntCluePoolCompany();
		YouxinBeanUtils.copyPropertiesIgnoreNull(poolPersonal, tbEntCluePoolCompany);
		//
		// tbEntCluePoolCompany.setId(bean.getId());
		// tbEntCluePoolCompany.setUpdateTime(time);
		// tbEntCluePoolCompany.setStatus(bean.getStatus());
		rowEffected = tbEntCluePoolCompanyMapper.updateByPrimaryKeySelective(tbEntCluePoolCompany);
		if (rowEffected != 1) {
			throw new BusinessException("更新线索状态失败");
		}

		TbEntCluePoolLog poolLog = new TbEntCluePoolLog();
		BeanUtils.copyProperties(sourceEntity, poolLog);
		YouxinBeanUtils.copyPropertiesIgnoreNull(poolPersonal, poolLog);
		poolLog.setCluePoolId(sourceEntity.getId());
		poolLog.setId(KeyGenerationUtils.generateKey());
		poolLog.setFlag(LeadsPoolType.StatusChange.getValue());
		poolLog.setOldStatus(sourceEntity.getStatus());

		poolLog.setMemberId(memberInfo.getId());
		poolLog.setMemberName(memberInfo.getUsername());
		poolLog.setRealName(memberInfo.getRealname());
		poolLog.setEntMemberId(userInfo.getEntMemberId());

		rowEffected = tbEntCluePoolLogMapper.insertSelective(poolLog);
		if (rowEffected != 1) {
			throw new BusinessException("更新线索状态失败");
		}
		return new ResponseObject();
	}

	/**
	 * @desc 线索流转
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseObject transferLeads(RequestTransferLeadsBean bean) {
		UserInfo userInfo = LoginAuth.getUserInfo();

		TbEntCluePoolCompany sourceEntity = tbEntCluePoolCompanyMapper.selectByPrimaryKey(bean.getId());
		if (sourceEntity == null) {
			throw new BusinessException("无法查询到线索信息");
		}
		
		if(sourceEntity.getEntIdentifyId()!=userInfo.getEntIdentifyId())
		{
			throw new BusinessException("当前线索不属于公司");
		}
		
		if (sourceEntity.getMemberId().longValue() == bean.getDestination()) {
			throw new BusinessException("线索不能流转给自己");
		}
		
		long time = System.currentTimeMillis();
		TbMemberInfo memberInfo = MemberRightsUtils.isMemberIdentifyAndPassed(tbMemberInfoMapper);

		Tuple<TbMemberInfo, TbEntMemberInfo> tuple=MemberRightsUtils.isMemberIdentify(tbMemberInfoMapper, tbEntMemberInfoMapper
				, bean.getDestination(), userInfo.getCompanyUid());
		TbMemberInfo destinationMemberInfo=tuple.getK();
		TbEntMemberInfo destinationEntMemberInfo=tuple.getV();
		TbEntCluePoolPersonal poolPersonal = new TbEntCluePoolPersonal();
		
		updateTransferLeads(poolPersonal, bean, time, destinationMemberInfo,destinationEntMemberInfo);

		int rowEffected = tbEntCluePoolPersonalMapper.updateByPrimaryKeySelective(poolPersonal);
		if (rowEffected != 1) {
			throw new BusinessException("流转线索失败");
		}

		TbEntCluePoolCompany tbEntCluePoolCompany = new TbEntCluePoolCompany();
		updateTransferLeads(tbEntCluePoolCompany, bean, time, destinationMemberInfo,destinationEntMemberInfo);

		
		rowEffected = tbEntCluePoolCompanyMapper.updateByPrimaryKeySelective(tbEntCluePoolCompany);
		if (rowEffected != 1) {
			throw new BusinessException("流转线索失败");
		}

		TbEntCluePoolLog poolLog = new TbEntCluePoolLog();
		BeanUtils.copyProperties(sourceEntity, poolLog);
		YouxinBeanUtils.copyPropertiesIgnoreNull(poolPersonal, poolLog);
		poolLog.setCluePoolId(sourceEntity.getId());
		poolLog.setId(KeyGenerationUtils.generateKey());
		poolLog.setFlag(LeadsPoolType.TransferLeads.getValue());
		poolLog.setOldEntMemberId(sourceEntity.getEntMemberId());
		poolLog.setOldRealName(sourceEntity.getRealName());
		

		rowEffected = tbEntCluePoolLogMapper.insertSelective(poolLog);
		if (rowEffected != 1) {
			throw new BusinessException("流转线索失败");
		}
		return new ResponseObject();
	}

	/**
	 * @desc 流转线索池
	 * @param leads
	 */
	private void updateTransferLeads(BaseEntCluePool leads, RequestTransferLeadsBean bean, long time,
			TbMemberInfo destinationMemberInfo,TbEntMemberInfo destinationEntMemberInfo) {
		leads.setId(bean.getId());
		leads.setUpdateTime(time);
		leads.setMemberId(destinationMemberInfo.getId());
		leads.setEntMemberId(destinationEntMemberInfo.getId());
		leads.setMemberName(destinationMemberInfo.getUsername());
		leads.setRealName(destinationMemberInfo.getRealname());
		leads.setDescription(bean.getDescription());
		leads.setCurrentFollowTime(time);
	}

	/**
	 * @desc 更新线索池状态
	 */
	@Override
	public void updateLeadsStatus(List<CompanyInfoBean> list, long entIdentifyId) {
		List<String> ids = list.stream().map((t) -> {
			return t.getUid();
		}).collect(Collectors.toList());
		if (ArrayUtils.isEmpty(ids)) {
			return;
		}
		QueryLeadsViewBean bean = new QueryLeadsViewBean();
		bean.setIds(ids);
		bean.setEntIdentifyId(entIdentifyId);
		List<TbEntCluePoolCompany> results = tbEntCluePoolCompanyMapper.selectByEntIdentifyIdLeads(bean);
		if (!ArrayUtils.isEmpty(results)) {
			for (CompanyInfoBean item : list) {
				for (TbEntCluePoolCompany poolCompany : results) {
					if (poolCompany.getCollectCompanyUid().equals(item.getUid())) {
						item.setFollowMemberName(poolCompany.getRealName());
						item.setFollowEntMemberId(poolCompany.getEntMemberId());
						item.setLeadsStatus(poolCompany.getStatus());
						break;
					}
				}
			}
		}
	}

	@Override
	public ResponseObject leadsHistory(RequestLeadsHistoryBean bean) {
		List<ResponseLeadsHistoryBean> list = tbEntCluePoolLogMapper.selectHistoryByLeadsId(bean.getId());
		bean.setResults(list);
		return new ResponseObject(list);
	}

	@Override
	public ResponseObject followList(MemberQueryListBean bean) {
		bean.setPageNo(1);
		bean.setPageSize(1000);
		UserInfo userInfo = LoginAuth.getUserInfo();
		List<MemberInfo> results = tbEntMemberInfoMapper.selectFollowList(userInfo.getEntIdentifyId());
		bean.setResults(results);
		return new ResponseObject(bean);
	}

	@Override
	public TbEntLeadsStat getTbEntLeadsStat(long id, long entMemberId) {
		// TODO Auto-generated method stub
		return leadsStatService.getTbEntLeadsStat(id, entMemberId);
	}
}
